<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts 分类标签居中示例</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.6.0/echarts.min.js"></script>
</head>
<body>
<div id="chart" style="width: 800px; height: 600px;"></div>
<script>
var chart = echarts.init(document.getElementById('chart'));

// 数据
var xAxisData = ["长裤", "短裤", "衬衣", "羊毛衫", "背心", "背心", "汗衫", "皮鞋"];
var xAxisGroupData = ["{offset|}裤子", "",  "衣服", "", "", "", "", "皮鞋"]; // 确保有 {offset|}
var groupSeparates = [false, false, true, false, false, false, false, true];
var seriesBarData = [15, 20, 10, 5, 15,20, 16, 10];

// 配置项
var option = {
    title: { text: '分类标签居中示例' },
    tooltip: {},
    grid: { top: 60, bottom: 120 },
    xAxis: [
        {
            position: "bottom",
            offset: 100,
            data: xAxisData,
            axisLabel: {
                align: 'center', // 水平居中对齐
                verticalAlign: 'middle', // 垂直居中对齐
                rotate: -90, // 文字旋转 -90 度，竖起来
                margin: 10 // 标签到轴线的距离
            }
        },
        {
            position: "bottom",
            offset: 20,
            data: xAxisGroupData,
            axisTick: {
                length: 40,
                interval: function(index, value) {
                    return groupSeparates[index]; // 根据标识分组的刻度线
                }
            },
            axisLabel: {
                align: 'center', // 水平居中对齐
                verticalAlign: 'middle', // 垂直居中对齐
                interval: 0,
                margin: 10,
                rich: {
                    offset: {
                        width: 0 // 初始宽度
                    }
                }
            }
        }
    ],
    yAxis: { type: 'value' },
    series: [
        {
            type: 'bar',
            
            data: seriesBarData
        }
    ],
    dataZoom: [
        {
            type: 'slider',
            xAxisIndex: [0, 1],
            start: 0,
            end: 100,
            height: 30,
            bottom: 40
        }
    ]
};

// 动态调整 offset
chart.lastBandWidth = 0;
chart.on('rendered', function () {
    var bandWidth = chart._chartsViews[0].renderTask.context.outputData._layout.bandWidth;
    console.log("bandWidth:", bandWidth); // 调试输出
    if (chart.lastBandWidth != bandWidth) {
        chart.lastBandWidth = bandWidth;
        setTimeout(() => {
            var optionNew = {xAxis: [{}, {}]};
            optionNew.xAxis[1] = {axisLabel: {rich: {offset: {width: chart.lastBandWidth}}}};
            chart.setOption(optionNew);
        }, 0);
    }
});

// 绘制图表
chart.setOption(option);
</script>
</body>
</html>